//var scrollItems = 10;
$(function() {
	var catsNumber = 5;
	var parallax = 101;
	
	var catBlocks = new Object();
	catBlocks.catNum = 0;
	catBlocks.getCategoryName = function(index) {
		for(var cat in this)
		{
			if(this[cat].index == index)
				return cat;
		}
	};
	createCatsObject(catBlocks);
	
	//$(".peMopho").peMopho();
	
	var car_params = {
					responsive: true,
					width: '100%',
					height: 94,
					auto: false,
					scroll: {
						//items: scrollItems,
						duration: 1000,
						easing: "easeOutExpo"
					},
					items: {
						width: 146,
						height: 70,
						visible: {
							max: 'auto'
						}
					},
					wipe: {
						onTouch: true,
						onMouse: true
					},
					mousewheel: {
						//items: scrollItems
					}/*,
					synchronise : [".another-b-elements .b-elements"]*/
	};
	
	$('.b-elements').mousewheel(function(event, delta) {
		console.log(delta);
		if ($(this).hasClass('first-b-elements'))
		{
			console.log('yes');
			moveSliders($(this), delta);
		}
		else
		{
			console.log('no');
			moveSliders($(this).parents('.category').find('.first-b-elements'), delta);
		}
		return false;
	});
	
	$('.first-b-elements').each(function() {
		car_params.synchronise = [ '#' + $(this).parents('.category').attr('id') + " .another-b-elements .b-elements" ];
		$(this).carouFredSel(car_params);
		$(this).parents('.category').find('.another-b-elements .b-elements').each(function() {
			$(this).carouFredSel({
					responsive: true,
					width: '100%',
					height: 94,
					auto: false,
					items: {
						width: 146,
						height: 70,
						visible: {
							max: 'auto'
						}
					}
			});
		});
	});
	/*$('.first-b-elements').carouFredSel(car_params);
	$('.another-b-elements .b-elements').carouFredSel({
					responsive: true,
					width: '100%',
					height: 94,
					auto: false,
					items: {
						width: 146,
						height: 70,
						visible: {
							max: 'auto'
						}
					}
	});*/
	//$('.element-item').hover(playVideo, stopVideo);
	
	$('.mini-prew').carouFredSel({
					responsive: true,
					width: '40%',
					height: 36,
					auto: false,
					scroll: {
						duration: 150,
					},
					items: {
						width: 77,
						height: 36,
						visible: {
							min: 1,
							max: 'auto'
						}
					},
					wipe: {
						onTouch: true,
						onMouse: true
					},
					mousewheel: {
						items: 1
					}
	});
	
	$('.mini-prew li').hover(darkImage, lightImage);
	
	$('.element-item').click(function () { showVideoBlock($(this), parallax); });

	
	$(window).resize(resizeActivePage);
	//$('.hideSlideButton').click(hideSlide);
	
	//Backbone--------------------------------------------------------------------------
	
	var Controller = Backbone.Router.extend({
		routes: {
			"": "main",
			"!/": "main",
			"!/:page": "page",
			/*"!/first": "first",
			"!/second": "second",*/
			"!/category/:cat": "category",
			"!/tag/:tag": "tag",
			"!/video/:video": "video",
			"!/category/up/:cat/:num": "categoryUp"
        },
		
		categoryUp: function(cat, num) {
			//allBlocksDown(parallax, true);
			moveBlockUp(catBlocks, cat, num, parallax, true);
		},
		
		main: function() {
			if (!isActivePage('main'))
			{
				hideVideoBlock(false);
				allBlocksDown(parallax, false)
				$('#main').animate({right: '0%'}, 800, function() {
					$('.activePage').animate({right: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#main').addClass('activePage');
					});
				});
			}
			else
			{
				hideVideoBlock(isVideoBlockShown());
				allBlocksDown(parallax, true);
			}
			
			setTimeout(hideSlide, 2000);
			
			/*hideVideoBlock(true);
			allBlocksDown(parallax, true);*/
			
			//moveBlockUp(catBlocks, 'titles', 3, parallax, true);
			/*$('.all_pages_block').hide("slide", { direction: "left" }, 1500);
			$('#main').show("slide", { direction: "right" }, 1500);*/
			/*$('.all_pages_block').slideUp(1500);
			$('#main').slideDown(1500);*/
			
			//$('#main').css({display:'block'});
			//$('#all_blocks').animate({left:'+' + $('#all_blocks').css('width')});
			/*$('.activePage').css({display:"none"});
			$('.activePage').removeClass('activePage');
			$('#main').addClass('activePage');*/
			
			/*if (!$('#main').hasClass('activePage'))
			{
				$('.activePage').css({zIndex:"100"});
				$('.activePage').removeClass('activePage');
				$('#main').addClass('activePage');
				$('.activePage').css({zIndex:"101"});
				$('#all_pages').animate({left: 0}, 1500);
			}*/
		},
		
		page: function(page) {
			$('.b-slide').remove();
			/*$('.content_block').hide("slide", { direction: "left" }, 1000);
			$('#second').show("slide", { direction: "right" }, 1000);*/
			/*$('.content_block').slideUp(1500);
			$('#second').slideDown(1500);*/
			$('#' + page).css('height', $('#content').css('height'));
			if (!isActivePage(page))
			{
				$('#' + page).animate({right: '0%'}, 800, function() {
					$('.activePage').animate({right: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#' + page).addClass('activePage');
					});
				});
				
				$('#' + page).css('width', $('#content').css('width'));
			}
		},
		
		/*page: function(page) {
			//alert(page);
			var page_id = '#' + page;
			var prevActivePage_id = '#' + $('.activePage').attr('id');
			$(prevActivePage_id).removeClass('activePage');
			$(page_id).addClass('activePage');
			//$(page_id).animate({left:'-' + $('#all_pages').css('width')}, 1500);
			$(page_id).animate({left:'0'}, 1500);
			$(page_id).css('width', '100%');
			$(prevActivePage_id).css('left', '100%');
		},*/
		
		first: function() {
			/*$('.all_pages_block').hide("slide", { direction: "left" }, 1500);
			$('#first').show("slide", { direction: "right" }, 1500);*/
			/*$('.all_pages_block').slideUp(1500);
			$('#first').slideDown(1500);*/
			
			$('.activePage').css({zIndex:"100"});
			$('.activePage').removeClass('activePage');
			$('#first').addClass('activePage');
			$('.activePage').css({zIndex:"101"});
			$('#all_pages').animate({right:'-' + $('#all_pages').css('width')}, 1500);
			$('#first').css('width', '100%');
		},
		
		second: function() {
			/*$('.all_pages_block').hide("slide", { direction: "left" }, 1500);
			$('#second').show("slide", { direction: "right" }, 1500);*/
			/*$('.all_pages_block').slideUp(1500);
			$('#second').slideDown(1500);*/
			
			//$('#second').css({display:'block'});
			//$('#all_blocks').animate({left:'+' + $('#all_blocks').css('width')});
			/*$('.activePage').css({display:"none"});
			$('.activePage').removeClass('activePage');
			$('#second').addClass('activePage');*/
			
			$('.activePage').css({zIndex:"100"});
			$('.activePage').removeClass('activePage');
			$('#second').addClass('activePage');
			$('.activePage').css({zIndex:"101"});
			$('#all_pages').animate({right:'-' + $('#all_pages').css('width')}, 1500);
			$('#second').css('width', '100%');
		},
		
		category: function(cat) {
			$('.b-slide').remove();
			/*
				есть такой же кусок кода в main
				возможно стоит это как-то упростить
			*/
			if (!isActivePage('main'))
			{
				hideVideoBlock(false);
				showCategory(cat, catsNumber, parallax, false);
				$('#main').animate({right: '0%'}, 800, function() {
					$('.activePage').animate({right: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#main').addClass('activePage');
					});
				});
			}
			else
			{
				hideVideoBlock(isVideoBlockShown());
				showCategory(cat, catsNumber, parallax, true);
			}
		},
		
		/*tag: function(tag) {
			$('.b-slide').remove();
			if (!isActivePage('tag'))
			{
				showTag(tag, false);
				$('#tag').animate({left: '0%'}, 1500, function() {
					$('.activePage').animate({left: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#tag').addClass('activePage');
					});
				});
			}
			else
			{
				showTag(tag, true);
			},
		}*/
		
		/*video: function(video) {
			showVideoBlock($(this), parallax);
		}*/
	});
	
	var controller = new Controller();

	Backbone.history.start();
});

function resizeActivePage()
{
	/*if (!$('#main').hasClass('activePage'))
		$('#all_pages').css('left', '-' + $('#all_pages').css('width'));*/
	/*if (isActivePage('main'))
		$('.category').css('width', $('#main').css('width'));*/
	$('.activePage').css('width', $('#content').css('width'));
}

function isActivePage(page_id)
{
	if ($('#' + page_id).hasClass('activePage'))
		return true;
	return false;
}

//console.log($('.category').eq(3).attr('class'));

function allBlocksDown(parallaxVal, animate)
{
	var one_parallax = 0;
	var animateTime = 800;
	
	if (!animate)
		animateTime = 0;
		
	$('.category').each(function() {
		$(this).animate({top: one_parallax}, animateTime);
		one_parallax += parallaxVal;
	});
}

/*
	(Array(object)) catObjects - ассоциативный массив объектов с описанием категорий
	(string) block - id сдвигаемого блока
	(int) upNum - количество позиций для сдвига
	(int) parallaxVal - высота одного слайдера
	(bool) animate - анимированный сдвиг (true) или нет (false)
*/

function moveBlockUp(catObjects, block, upNum, parallaxVal, animate)
{
	var firstCatID = '#' + $('.category').eq(0).attr('id');
	console.log(firstCatID);
	var blockID = '#' + block;
	var currentCatZindex = $(blockID).css('z-index');
	
	$(blockID).stop(false, false);
	//var upPixels = $(blockID).css('top') - upNum * parallaxVal;
	var futureIndex = 0;
	//var shift = upNum;
	if (catObjects[block].index > upNum)
	{
		futureIndex = catObjects[block].index - upNum;
	}
	/*else if (catObjects[block].index - upNum < 0)
	{
		shift = catObjects[block].index;
	}*/
			
	console.log(futureIndex);
		
	var upPixels = catObjects[block].index*parallaxVal - upNum * parallaxVal;
	
	if (upPixels < 0)
	{
		upPixels = 0;
	}
	
	var animateTime = 2000;
	
	if (!animate)
		animateTime = 0;
	
	$(blockID).animate({top: upPixels}, animateTime, function() {
		/*console.log(shift);
        for (var i=0; i!=shift; ++i) {
            var temp = catObjects[catObjects.getCategoryName(i)];
            for (var j=i; j!=catObjects.catNum-1; ++j) {
				console.log(j);
				catObjects[catObjects.getCategoryName(j)].zIndex = catObjects[catObjects.getCategoryName(j+1)].zIndex;
				catObjects[catObjects.getCategoryName(j)].index = catObjects[catObjects.getCategoryName(j+1)].index;
            }
           catObjects[catObjects.getCategoryName(catObjects.catNum-1)].index =  temp.index;
		   catObjects[catObjects.getCategoryName(catObjects.catNum-1)].zIndex = temp.zIndex;
        }
       
	   console.log(catObjects);
	   
	   var one_parallax = parallaxVal * shift + parseInt($(blockID).css('top'));
	   console.log(one_parallax);
	   $($(blockID).prevAll('.category').get().reverse()).each(function() {
			if ($(blockID).nextAll('.category').size() > 0)
			{
				$(blockID).nextAll('.category:last').after($(this));
			}
			else
			{
				$(blockID).after($(this));
			}
			
			$(this).animate({top: one_parallax}, animateTime);
			one_parallax += parallaxVal;
		});*/
	});
	//$(blockID).stop();
	//дальше смена свойств сдвигаемого объекта и тех, которые он перекрыл + их перемещение
}

function createCatsObject(object)
{
	$('.category').each(function() {
		var catID = $(this).attr('id');
		object[catID] = new Object();
		object[catID].zIndex = $(this).css('z-index');
		//object[catID].visibleRows = 1;
		object[catID].index = $(this).index();
		object.catNum++;
	});
}

function showVideoBlock(obj, parallaxVal) 
{
	console.log(obj.parents('.category').find('.video-wrap').css('display'));
	if (obj.parents('.category').find('.video-wrap').css('display') == 'none')
		hideVideoBlock(true);
	var video_id = obj.find('a').attr('href').split('/')[2];
	/*$('.video-wrap iframe').attr('src', 'http://player.vimeo.com/video/' + video_id + '?title=0&amp;byline=0&amp;portrait=0&amp;badge=0&amp;player_id=player&amp;api=1');
	obj.parents('.category').find('.row-category:first .row-title').after($('.video-wrap'));*/
	
	obj.parents('.category').find('.video-wrap iframe').attr('src', 'http://player.vimeo.com/video/' + video_id + '?title=0&amp;byline=0&amp;portrait=0&amp;badge=0&amp;player_id=player&amp;api=1');
	
	obj.parent('ul').trigger("slideTo", 
		[obj, "next", 1, {duration: 1500}]);
		
	//$('#main').before($('#video').animate({height: 'toggle', width: 'toggle'}, 2000));
	//$('#video').show('scale', {}, 2000);
	setTimeout(function() {obj.parents('.category').find('.video-wrap').show(2000, function() {
		$('.video-wrap .tags').show('fold', { direction: "right" }, 1000);
	});}, 1500);
	
	/*
		!!!
		если переход к видео будет происходить со страницы тега (или с люой другой страницы,
		которая не является главной)
		то категорию мне таким способом не узнать
		!!!!
	*/
	showCategory(obj.parents('.category').attr('id'), $('.category').size(),  parallaxVal, true);
	
	//$('#video').animate({height: 'toggle', width: 'toggle', top: 0}, 2000);
}

function showCategory(cat, catsNumber, parallax, animate) 
{
	var blockID = '#' + cat;
			
	//$(blockID).stop(false, false);
				
	var upPixels = 0;			
	var animateTime = 800;
	
	if (!animate)
		animateTime = 0;
			
	$(blockID).animate({top: upPixels}, animateTime, function() {
		var currentZIndex = $(blockID).css('z-index');
		if ($(blockID).next('.category').size() > 0)
			$(blockID).css('z-index', $(blockID).next('.category').css('z-index'));
		var one_parallax_first;
		var newZIndex_first = catsNumber - currentZIndex + 2;
		$($(blockID).prevAll('.category').get().reverse()).each(function() {
			if ($(blockID).nextAll('.category').size() > 0)
			{
				$(blockID).nextAll('.category:last').after($(this));
			}
			else
			{
				$(blockID).after($(this));
			}
					
			one_parallax_first = parallax * 4 + (newZIndex_first - 2) * parallax;
			$(this).animate({top: one_parallax_first}, 0);
			//$(this).css('z-index', newZIndex_first++);
		});
		
		var newZIndex_second = 3;
		var one_parallax_second = parallax * 4;
		var nextCategory = $(blockID).next('.category').attr('id');
		$(blockID).next('.category').animate({top: one_parallax_second}, animateTime, function(){
			$(this).css('z-index', 2);
		});
		one_parallax_second += parallax;
		$(blockID).next('.category').nextAll('.category').each(function() {
			$(this).animate({top: one_parallax_second}, 0, function(){
				if (newZIndex_second + 1 >= 5)
					$(blockID).css('z-index', 1);
			});
			$(this).css('z-index', newZIndex_second++);
			one_parallax_second += parallax;;
		});
	});
}

function hideVideoBlock(animate)
{
	var animateTime = 1500;
	if (!animate)
		animateTime = 0;
		
	$('.video-wrap').slideUp(animateTime, function() {
		$('.video-wrap .tags').hide(animateTime);
	});
}

function darkImage()
{
	$(this).addClass('active');
}

function lightImage()
{
	$(this).removeClass('active');
}

function showTag(tag, animate)
{
	var animateTime = 2000;
	if (!animate)
		animateTime = 0;
		
	$('#tag').append($('#tag_template').html());
	$('.row-title a').text(tag);
	
	$('.tag_template_inside').slideDown(animateTime, function() {
		$('.tag_template_inside').prevAll().remove();
	});
}

function isVideoBlockShown()
{
	if ($('.video-wrap').css('display') == 'none')
		return false;
	else
		return true;
}

// возвращает cookie если есть или undefined
function getCookie(name) {
	var matches = document.cookie.match(new RegExp(
	  "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
	))
	return matches ? decodeURIComponent(matches[1]) : undefined 
}

// уcтанавливает cookie
function setCookie(name, value, props) {
	props = props || {}
	var exp = props.expires
	if (typeof exp == "number" && exp) {
		var d = new Date()
		d.setTime(d.getTime() + exp*1000)
		exp = props.expires = d
	}
	if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }

	value = encodeURIComponent(value)
	var updatedCookie = name + "=" + value
	for(var propName in props){
		updatedCookie += "; " + propName
		var propValue = props[propName]
		if(propValue !== true){ updatedCookie += "=" + propValue }
	}
	document.cookie = updatedCookie

}

// удаляет cookie
function deleteCookie(name) {
	setCookie(name, null, { expires: -1 })
}


function hideSlide()
{
	var animateTime = 1000;
	setCookie ('slideHide', true);
	$('.b-slide').css('z-index', '110');
	
	$('.b-slide').animate({left: '-100%'}, animateTime, function(){
		$('.over-b-slide').remove();
	});
}

function playVideo()
{
	/*playerID = 'player' + playerID;
	
	var newObj = $('.video-frame').clone();
	newObj.attr('id', playerID);
	
	console.log($('body').prepend(newObj));
	
	$('#'+playerID).css('margin', (obj.offset().top - 5) + 'px 0px 0px' + (obj.offset().left - 5) + 'px');
	newObj.fadeIn();
	
	console.log((obj.offset().top - 5) + 'px 0px 0px ' + (obj.offset().left - 5) + 'px');*/
	
	//$f(document.getElementById(playerID)).addEvent('ready', ready);
	
	var preview = $(this).find('.video-frame');
	preview.fadeIn(1500);
	console.log(preview.find('iframe').attr('id'));
	$f(document.getElementById(preview.find('iframe').attr('id'))).addEvent('ready', ready)
}

function stopVideo()
{
	
	$(this).find('.video-frame').fadeOut('fast');
}

function moveSliders(obj, delta)
{
	if (delta < 0)
		obj.trigger("prev", 'auto');
	else
		obj.trigger("next", 'auto');
}